package com.kkd.kkdapp.activity;

import java.util.ArrayList;
import java.util.List;

import android.app.Dialog;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.kkd.kkdapp.R;
import com.kkd.kkdapp.adapter.PrivilegeGridViewAdapter;
import com.kkd.kkdapp.adapter.PrivilegeGridViewAdapter.OnItemclick;
import com.kkd.kkdapp.adapter.PrivilegeViewPagerAdapter.OnViewPagerItemListener;
import com.kkd.kkdapp.base.BaseActivity;
import com.kkd.kkdapp.db.CurUserModel;
import com.kkd.kkdapp.db.app.model.User;
import com.kkd.kkdapp.http.entity.Privilege;
import com.kkd.kkdapp.http.entity.PrivilegeData;
import com.kkd.kkdapp.http.entity.RiskAssessment;
import com.kkd.kkdapp.http.manager.HttpCallBack;
import com.kkd.kkdapp.http.manager.KkdHttpMagager;
import com.kkd.kkdapp.listener.OnSingleClickListener;
import com.kkd.kkdapp.utils.AppUtil;
import com.kkd.kkdapp.utils.DialogUtils;
import com.kkd.kkdapp.utils.LogUtil;
import com.kkd.kkdapp.utils.PreferenceUtils;
import com.kkd.kkdapp.utils.SystemUtils;
import com.kkd.kkdapp.view.RoundImageView;
import com.nostra13.universalimageloader.core.ImageLoader;

/****
 * 
 * @Data 2016-03-11
 * 
 * @author mty
 * 
 * @Name 我的
 * 
 */
public class MyActivity extends BaseActivity implements OnClickListener {

	private final int PRIVILEGE_INT = 101;// 拿特权结果码
	private final int PRIVILEGE_CODE_ZERO = 3;
	private final int PERSONAL_INFORMATION = 105;

	private RelativeLayout top_img; // 返回
	private RelativeLayout account_rl; // 个人信息
	private RoundImageView account_rl_img; // 头像
	private RelativeLayout set_rl; // 设置
	private TextView set_nickname; // 昵称是否设置
	private PopupWindow mPopupWindow;
	private List<Privilege> arr = new ArrayList<Privilege>();
	private List<Privilege> bigArr = new ArrayList<Privilege>();
	private RecyclerView recyclerview;
	private Dialog privilegeDialog; // 特权Dialog
	private LinearLayout privilege_ll; // 特权
	private TextView number_privileges_tv; // 我拥有特权个数
	private ImageView icon_one;
	private RelativeLayout privileges_rl;
	private PrivilegeGridViewAdapter adapter;
	private View view_top;
	private View call_toService;
	private Dialog dialog_service;
	private RelativeLayout as_bt; // 账户安全
	private RelativeLayout feedback; // 用户反馈
	private TextView assesType_tv; // 风险评估类型
	private String assesUrl; // 风险评估Url
	private RelativeLayout asses_rl; // 风险评估栏
	private Dialog assessmentDialog; // 风险评估Dialog
	private boolean isAssesStaus; // true今年已评估，false今年未评估

	private Handler mHandler = new Handler() {

		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case PRIVILEGE_CODE_ZERO:
				PrivilegeData data = (PrivilegeData) msg.obj;
				if (data.getStatus() == 0) { // 0： 不展示特权
					privilege_ll.setVisibility(View.GONE);
				} else if (data.getStatus() == 1) { // 1：展示特权
					privilege_ll.setVisibility(View.VISIBLE);
				}
				number_privileges_tv.setText(data.getPrivilegesTips());
				int priSubpageStatus = data.getPriSubpageStatus();
				if (priSubpageStatus == 0) {
					privileges_rl.setClickable(false);
					icon_one.setVisibility(View.INVISIBLE);
				} else if (priSubpageStatus == 1) {
					privileges_rl.setClickable(true);
					icon_one.setVisibility(View.VISIBLE);
				}
				arr.clear();
				arr.addAll(data.getDataList());
				adapter.notifyDataSetChanged();
				RiskAssessment asses = data.getAsses();
				if (asses != null) {
					assesType_tv.setText(asses.getAssesType());
					assesUrl = asses.getAssesUrl();
					isAssesStaus = asses.isAssesStatus();

				}
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_my);
		initView();
		setListener();
	}

	/**********
	 * 初始化控件
	 **********/
	public void initView() {
		call_toService = this.findViewById(R.id.call_toService);
		top_img = (RelativeLayout) this.findViewById(R.id.top_img);
		account_rl = (RelativeLayout) this.findViewById(R.id.account_rl);
		account_rl_img = (RoundImageView) this
				.findViewById(R.id.account_rl_img);
		set_rl = (RelativeLayout) this.findViewById(R.id.set_rl);
		set_nickname = (TextView) this.findViewById(R.id.set_nickname);
		recyclerview = (RecyclerView) this.findViewById(R.id.recyclerview);
		recyclerview.setLayoutManager(new StaggeredGridLayoutManager(1,
				StaggeredGridLayoutManager.HORIZONTAL));
		privilege_ll = (LinearLayout) this.findViewById(R.id.privilege_ll);
		number_privileges_tv = (TextView) this
				.findViewById(R.id.number_privileges_tv);
		icon_one = (ImageView) this.findViewById(R.id.icon_one);
		as_bt = (RelativeLayout) this.findViewById(R.id.as_bt);
		feedback = (RelativeLayout) this.findViewById(R.id.feedback);
		privileges_rl = (RelativeLayout) this.findViewById(R.id.privileges_rl);
		adapter = new PrivilegeGridViewAdapter(MyActivity.this, arr);
		recyclerview.setAdapter(adapter);
		adapter.setOnItemclick(new OnItemclick() {

			@Override
			public void getPosition(int position) {
				LogUtil.e("TAG", "position----->" + position);
				if (!TextUtils.isEmpty(arr.get(position).getImage_big())) {
					if (AppUtil.isConnect(MyActivity.this)) {
						myPrivilegeDialog(position + 1);
					} else {
						Toast mToast = Toast.makeText(MyActivity.this, "网络异常!",
								Toast.LENGTH_SHORT);
						mToast.setGravity(Gravity.BOTTOM, 0, 0);
						mToast.show();
					}
				}
			}
		});
		view_top = this.findViewById(R.id.view_top);
		if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
			view_top.setVisibility(View.GONE);
		}
		assesType_tv = (TextView) this.findViewById(R.id.assesType_tv);
		asses_rl = (RelativeLayout) this.findViewById(R.id.asses_rl);
	}

	@Override
	protected void onResume() {
		super.onResume();
		User user = CurUserModel.getCurUser();
		if (user != null && user.state == 0) { // 用户不为空且已登陆
			queryPrivilege();
		} else {
			finish();
			return;
		}
		// 头像
		ImageLoader.getInstance().displayImage(
				PreferenceUtils.getInstance().getHeadUrl(this), account_rl_img);
		// 手机号
		String phone = PreferenceUtils.getInstance().getPhone(this);
		if (!PreferenceUtils.getInstance().getNickname(this).equals(phone)) {
			set_nickname.setText(PreferenceUtils.getInstance()
					.getNickname(this));
		} else {
			set_nickname.setText("尚未设置昵称");
		}
	}

	/*********
	 * 注册监听事件
	 *********/
	public void setListener() {
		top_img.setOnClickListener(this);
		account_rl.setOnClickListener(this);
		set_rl.setOnClickListener(this);
		privileges_rl.setOnClickListener(this);
		privileges_rl.setClickable(false);
		as_bt.setOnClickListener(this);
		feedback.setOnClickListener(this);
		asses_rl.setOnClickListener(this);
		call_toService.setOnClickListener(new OnSingleClickListener() {

			@Override
			public void onSingleClick(View v) {
				showDialog("客服电话：4000-137-000");
			}
		});
	}

	Intent intent;

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.top_img: // 返回
			finish();
			break;
		case R.id.account_rl: // 个人信息
			SystemUtils.onEvent("Account_Sett_Personal", 1);
			intent = new Intent(this, PersonalInformationActivity.class);
			startActivityForResult(intent, PERSONAL_INFORMATION);
			break;
		case R.id.set_rl: // 设置
			SystemUtils.onEvent("Account_Sett_FeedBack", 1);
			intent = new Intent(this, SetUpActivity.class);
			startActivity(intent);
			break;
		case R.id.as_bt: // 账户安全
			intent = new Intent(this, AccountSecurityActivity.class);
			startActivity(intent);
			break;
		case R.id.feedback: // 用户反馈
			SystemUtils.onEvent("Account_Sett_FeedBack", 1);
			intent = new Intent(this, FeedbackActivity.class);
			startActivity(intent);
			break;
		case R.id.asses_rl: // 风险评估
			if (!TextUtils.isEmpty(assesUrl)) {
				if (isAssesStaus) {
					intent = new Intent(MyActivity.this, KKDWebActivity.class);
					intent.putExtra("url", assesUrl);
					startActivity(intent);
				} else {
					assessmentDialog();
				}
			}
			break;
		default:
			break;
		}
	}

	/************
	 * 风险评估弹窗
	 ************/
	public void assessmentDialog() {
		if (assessmentDialog != null) {
			assessmentDialog.cancel();
			assessmentDialog = null;
		}
		assessmentDialog = DialogUtils.assessmentDialog(this, "保守型",
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						intent = new Intent(MyActivity.this,
								KKDWebActivity.class);
						intent.putExtra("url", assesUrl);
						startActivity(intent);
						assessmentDialog.dismiss();
					}
				});
		assessmentDialog.show();
	}

	/*******
	 * 特权Dialog
	 *******/
	public void myPrivilegeDialog(int position) {
		if (privilegeDialog != null) {
			privilegeDialog.cancel();
			privilegeDialog = null;
		}
		for (int i = 0; i < arr.size(); i++) {
			if (!TextUtils.isEmpty(arr.get(i).getImage_big())) {
				Privilege mPrivilege = new Privilege();
				mPrivilege.setStatus(arr.get(i).getStatus());
				mPrivilege.setImage_big(arr.get(i).getImage_big());
				mPrivilege.setTitle(arr.get(i).getTitle());
				bigArr.add(mPrivilege);
			}
		}
		privilegeDialog = DialogUtils.privilegeDialog(this, bigArr, position,
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						switch (v.getId()) {
						case R.id.close_img:
							if (privilegeDialog != null
									&& privilegeDialog.isShowing()) {
								privilegeDialog.dismiss();
								privilegeDialog.cancel();
								privilegeDialog = null;
							}
							break;
						}
					}
				}, new OnViewPagerItemListener() {

					@Override
					public void clickItem(int position) {
						if (privilegeDialog != null
								&& privilegeDialog.isShowing()) {
							privilegeDialog.dismiss();
							privilegeDialog.cancel();
							privilegeDialog = null;
							setResult(PRIVILEGE_INT);
							finish();
						}
					}
				});
		privilegeDialog.show();
	}

	/*************
	 * 我的特权接口
	 *************/
	public void queryPrivilege() {
		KkdHttpMagager.getInstance().queryPrivilege(new HttpCallBack() {

			@Override
			public void onSuccess(int statusCode, Object responseBody) {
				PrivilegeData data = (PrivilegeData) responseBody;
				Message msg = new Message();
				msg.what = PRIVILEGE_CODE_ZERO;
				msg.obj = data;
				mHandler.sendMessage(msg);
			}

			@Override
			public void onFailure(int statusCode, String desc) {

			}
		});
	}

	/**
	 * 拨打客服电话对话框
	 * 
	 * @param message
	 */
	private void showDialog(String message) {
		if (dialog_service != null) {
			dialog_service.cancel();
			dialog_service = null;
		}
		dialog_service = DialogUtils.callService(MyActivity.this);
		dialog_service.show();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == PERSONAL_INFORMATION
				&& resultCode == PersonalInformationActivity.SAFE_EXIT_RESULTCODE) {
			finish();
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (mPopupWindow != null) {
			mPopupWindow.dismiss();
			mPopupWindow = null;
		}
		if (privilegeDialog != null) {
			privilegeDialog.cancel();
			privilegeDialog = null;
		}
		if (dialog_service != null) {
			dialog_service.cancel();
			dialog_service = null;
		}
		if (assessmentDialog != null) {
			assessmentDialog.cancel();
			assessmentDialog = null;
		}
	}

}
